import React from "react";
import {connect} from "react-redux";
import {goback} from "shared/actions";
import {BaseComponent} from "fe-lib";
import {ENUM_OPERATION} from "shared/utils/enumerate";
import {Icon, Spin, Modal} from "antd";
import ErrorTip from "shared/components/ErrorTip";
import ErrorAlert from "shared/components/ErrorAlert";
import {apiIsLoading, apiIsRealLoading, apiIsError} from "shared/utils/reducerUtil";
import * as actions from "../../actions";
import * as actionTypes from "../../consts";
import Form from "./Form";

class CrudModal extends BaseComponent {
  state = {}

  componentDidMount() {
    this.reload();
  }

  reload = () => {
    const {operation} = this.props;
    if (operation === ENUM_OPERATION.MODIFY) {
      const {match: {params: {id}}} = this.props;
      this.props.getFormData(id);
    } else {
      // 调用初始化
      this.props.initFormData();
    }
  }
  getFormInputData = (callback) => {
    this.formRef.validateFields((errors, fields) => {
      if (errors) {
        return;
      }
      callback(fields);
    });
  }
  onSave = () => {
    this.getFormInputData((data) => {
      this.props.temp2redux(data);
      const {match: {params: {id}}} = this.props;
      if (id) {
        const putData = {...data, id};
        this.props.putForm(putData);
      } else {
        this.props.postForm(data);
      }
    });
  }

  render() {
    const {formData, formStatus} = this.props;
    const formAjax = apiIsRealLoading(formStatus);
    const operationLoading = apiIsLoading(formData) || formAjax;
    const formProps = formData.get('data').toJS();

    const modalProps = {
      closable: !formAjax,
      title: this.props.title,
      onOk: this.onSave,
      visible: true,
      icon: <Icon type="frown"/>
    };
    if (!formAjax) {
      modalProps.onCancel = this.props.goback;
      modalProps.onClose = this.props.goback;
    }
    return (
      <Modal {...modalProps}>
        {
          apiIsError(formData) ?
            <ErrorTip prompt={formData.get('message')} reload={this.reload}/> :
            <Spin spinning={operationLoading}>
              <ErrorAlert error={apiIsError(formStatus)} message={formStatus.get('message')} type="error"/>
              <Form
                ref={(formRef) => {
                  this.formRef = formRef;
                }}
                loading={operationLoading}
                {...formProps}
              />
            </Spin>
        }
      </Modal>
    );
  }
}

const {formData, formStatus} = actionTypes.key;
const mapStateToProps = (state) => {
  const {datasource} = state;
  return {
    formData: datasource.get(formData),
    formStatus: datasource.get(formStatus),
  };
};

const mapDispatchProps = {
  goback,
  initFormData: actions.initFormData,
  getFormData: actions.getFormData,
  postForm: actions.postForm,
  putForm: actions.putForm,
  temp2redux: actions.temp2redux,
};

export default connect(mapStateToProps, mapDispatchProps)(CrudModal);
